package com.sense.kukoo.biz_me.view

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseUser
import com.linecorp.linesdk.LineProfile
import com.sense.feel.common.global.bean.WebPage
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_me.R
import com.sense.kukoo.biz_me.databinding.BizMeActivityLoginBinding
import com.sense.kukoo.biz_me.login.core.*
import com.sense.kukoo.biz_me.login.core.callback.OnFacebookLoginCallback
import com.sense.kukoo.biz_me.login.core.callback.OnGoogleLoginCallback
import com.sense.kukoo.biz_me.login.core.callback.OnLineLoginCallback
import com.sense.kukoo.biz_me.vm.LoginViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.kv.login_history.LoginHistory
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_ME_MODULE_LOGIN_ACTIVITY)
class LoginActivity : BaseMvvmActivity<LoginViewModel, BizMeActivityLoginBinding>() {

    private val TAG: String = javaClass.simpleName

    override fun getLayoutId(): Int = R.layout.biz_me_activity_login

    override fun getViewModelClass(): Class<LoginViewModel> = LoginViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        mBinding.titleView.init(this, "", false)
        setSupportActionBar(mBinding.titleView)
        //
        bindAction(mViewModel.action_toFacebook){
            FacebookLoginManager.login(this)
        }
        bindAction(mViewModel.action_toLine){
            LineLoginManager.lineLogin(this)
        }
        bindAction(mViewModel.action_toGoogle){
            GoogleLoginManager.signIn(this)
        }
        bindAction(mViewModel.action_toPhone){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_ME_MODULE_PHONE_NUMBER_ACTIVITY)
                .navigation()
        }
        //
        initThirdLogin()
    }

    override fun initView() {
        initProtocol()
        //
        val lastLoginType = Repo.loginHistory.lastLoginType()
        var type = ""
        when (lastLoginType) {
            LoginHistory.SOURCE_INNER -> {
                type = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_type_hint_type_phone)
            }
            LoginHistory.SOURCE_FACEBOOK -> {
                type = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_type_hint_type_facebook)
            }
            LoginHistory.SOURCE_GOOGLE -> {
                type = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_type_hint_type_google)
            }
            LoginHistory.SOURCE_LINE -> {
                type = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_type_hint_type_line)
            }
        }
        if(type.length > 0){
            val hint = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_type_hint, type)
            mBinding.tvHintLogin.text = hint
            mBinding.tvHintLogin.visibility = View.VISIBLE
        }
    }

    private fun initProtocol() {
        val text1 = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_protocol_text_1)
        val text2 = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_protocol_text_2)
        val text3 = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_protocol_text_3)
        val text4 = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.login_protocol_text_4)
        val color = ApplicationContext.getColor(R.color.btn_protocol_red)
        val click1 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                    .withParcelable(ConstantConfig.ARG1, WebPage(url = ConstantConfig.URL.h5TermsOfService()))
                    .navigation()
            }

            override fun updateDrawState(ds: TextPaint) = ds.setColor(color)
        }
        val click2 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                    .withParcelable(ConstantConfig.ARG1, WebPage(url = ConstantConfig.URL.h5PrivacyPolicy()))
                    .navigation()
            }

            override fun updateDrawState(ds: TextPaint) = ds.setColor(color)
        }
        //
        val spannable = SpannableStringBuilder()
        spannable.append(text1)
            .append(text2, click1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            .append(text3)
            .append(text4, click2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //
        mBinding.tvProtocol.text = spannable
        mBinding.tvProtocol.movementMethod = LinkMovementMethod.getInstance()
        mBinding.tvProtocol.highlightColor = Color.TRANSPARENT
    }

    private fun initThirdLogin(){
        GoogleLoginManager.initGoogleLoginConfig(this)
        LineLoginManager.initLine()
        FacebookLoginManager.initFacebookLoginConfig(this, object : OnFacebookLoginCallback {
            override fun onSuccess(firebaseUser: FirebaseUser) {
                with(firebaseUser) {
                    var avatar = firebaseUser.photoUrl?.scheme + "://" + firebaseUser.photoUrl?.host + firebaseUser.photoUrl?.path
                    displayName?.let { mViewModel.login(avatar, LoginHistory.SOURCE_FACEBOOK, it, uid) }
                }
            }

            override fun onFail(msg: String) {
                hideLoadingDialog()
                Toast.makeText(this@LoginActivity, msg, Toast.LENGTH_SHORT).show()
            }

            override fun onCancel() {
                hideLoadingDialog()
                Toast.makeText(this@LoginActivity, "用戶已取消", Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        LoggerManager.e(TAG, "resultCode=" + resultCode)
        LoggerManager.e(TAG, "requestCode=" + requestCode)
        LoggerManager.e(TAG, "data=" + data?.data)
        LoggerManager.e(TAG, "extras=" + data?.extras.toString())
        //
        if (requestCode == GOOGLE_REQUEST_CODE) {
            googleLogin(data)
        } else if (requestCode == FACEBOOK_RESULT_CODE) {
            FacebookLoginManager.onActivityResult(requestCode, resultCode, data)
        } else if (requestCode == LineLoginManager.LINE_REQUEST_CODE) {
            LineLoginManager.lineLoginCallBack(requestCode, data, object : OnLineLoginCallback {
                override fun onSuccess(lineProfile: LineProfile) {
                    with(lineProfile) {
                        var avatar =
                            lineProfile.pictureUrl?.scheme + "://" + lineProfile.pictureUrl?.host + lineProfile.pictureUrl?.path
                        mViewModel.login(avatar, LoginHistory.SOURCE_LINE, displayName, userId)
                    }
                }

                override fun onFail(msg: String) {
                    hideLoadingDialog()
                }

                override fun onCancel() {
                    hideLoadingDialog()
                }

            })
        }
    }

    private fun googleLogin(data: Intent?) {
        try {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            val account = task.getResult(ApiException::class.java)
            LoggerManager.e(TAG, "firebaseAuthWithGoogle_id=" + account.id)
            LoggerManager.e(TAG, "firebaseAuthWithGoogle_Token=" + account.idToken)
            GoogleLoginManager.firebaseAuthWithGoogle(
                    this,
                    account,
                    object : OnGoogleLoginCallback {
                        override fun onSuccess(firebaseUser: FirebaseUser) {
                            with(firebaseUser) {
                                var avatar =
                                    firebaseUser.photoUrl?.scheme + "://" + firebaseUser.photoUrl?.host + firebaseUser.photoUrl?.path
                                displayName?.let { mViewModel.login(avatar, LoginHistory.SOURCE_GOOGLE, it, uid) }
                            }
                        }

                        override fun onFail(msg: String) {
                            LoggerManager.e(TAG, "onFail=" + msg)
                            hideLoadingDialog()
                        }

                    })
        } catch (e: ApiException) {
            LoggerManager.e(TAG, "Exception=" + e.message)
            hideLoadingDialog()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}